<?php
namespace Admin\Controller;
use Think\Controller;
class DataController extends CommonController{
    //添加数据
    public function add(){
        if(IS_POST){
            //处理post
            $post = I('post.');
            //dump($post);die;
            
            //实例化模型
            $model = D('Data');
            //数据保存
            $result = $model -> addData($post,$_FILES['kid']);

            if($result){
                $this -> success('添加成功!',U('showList'),3);
            }else{
                $this -> error('添加失败!');
            }
        }else{
            //展示模板
            $model = M('Category');
            $data = $model -> order('id desc') -> select();
            $this -> assign('data',$data);
            $this -> display();
        }
    }
    //数据列表
    public function showList(){
        //模型实例化
        $model = M('Data');
        //分页第一步：查询总的记录数
        $yw2 = I('get.yw2');
        if(empty($yw2)){
            $count = $model -> count();
        }else{
            $where = "yw2 like '%" . $yw2 . "%'";
            $count = $model -> where($where) -> count();
        }
        //dump($count);die;
        //分页第二步：实例化分页类，传递参数
        $page = new \Think\Page($count,10);  //每页显示1个
        //分页第三步：可选步骤，定制分页按钮的提示文字
        $page -> rollPage = 10;
        $page -> lastSuffix = false;
        $page -> setConfig('prev','上一页');
        $page -> setconfig('next','下一页');
        $page -> setconfig('last','末页');
        $page -> setconfig('first','首页');
        //分页第四步：通过show方法输出分页的URL链接
        $show = $page -> show();
        $show = bootstrap_page_style($show);
        //dump($show);die;
        //分页第五步：使用limit方法查询数据
        
        //dump(empty($yw2));die;
        if(empty($yw2)){
            $data = $model -> limit($page -> firstRow,$page -> listRows) -> order('addtime desc') -> select();
        }else{
            //$where = "yw2 like '%" . $yw2 . "%'";
            //dump($where);die;
            $data = $model -> where($where) -> limit($page -> firstRow,$page -> listRows) -> order('addtime desc') -> select();
        }
        
        //dump($data);die;
        //分页第六步：传递给模板
        $this -> assign('data',$data);
        $this -> assign('show',$show);
        //分页第七步：展示模板
        C('TOKEN_ON',false);//动态关闭表单令牌验证
        $this -> display();
    }
    //编辑数据
    public function edit(){
        if(IS_POST){
            //实例化模型类
            $model = D('Data');
            $data = $model -> create();
            //dump($data);die;

            if(!$data){
                //提标用户验证失败
                //echo $model -> getError();die;
                //dump($model -> getError());die;
                $this -> error($model -> getError());exit;
            }

            $data['addtime'] = time();            
            //dump($data);die;

            $result = $model -> save($data);
            if($result){
                $this -> success('修改成功！',U('showList'));
                //$this -> redirect('Admin/Category/showList');
            }else{
                $this -> error('修改失败！');
            }
        }else{
            //接收id
            $id = I('get.id');
            //sql=select t1.*,t2.folder as folder from yh_data as t1 left join yh_category as t2 on t1.category_id = t2.id where t1.id = get.id
            //获取数据
            $data = M('Data') -> field('t1.*,t2.folder as folder')
                            -> alias('t1')
                            -> join('left join yh_category as t2 on t1.category_id = t2.id')
                            -> where('t1.id = ' . $id)
                            -> find();
            //dump($data);die;
            //图片路径拼接一下
            $data['kid'] = '/Uploads/' . $data['folder'] . '/' . $data['kid'];
            //判断边款
            //dump(is_null($data['biankuan1']));die;
            if(!is_null($data['biankuan1'])){
                $data['biankuan1'] = '/Uploads/' . $data['folder'] . '/' . $data['biankuan1'];
            }
            if(!is_null($data['biankuan2'])){
                $data['biankuan2'] = '/Uploads/' . $data['folder'] . '/' . $data['biankuan2'];
            }
            if(!is_null($data['biankuan3'])){
                $data['biankuan3'] = '/Uploads/' . $data['folder'] . '/' . $data['biankuan3'];
            }
            if(!is_null($data['biankuan4'])){
                $data['biankuan4'] = '/Uploads/' . $data['folder'] . '/' . $data['biankuan4'];
            }
            //dump($data);die;
            $this -> assign('data',$data);
            //展示模板
            $this -> display();
        }
    }

    //上传图片
    public function uploadImg(){
        //dump($_GET);die;
        if(IS_POST){
            //接收post数据
            $post = I('post.');//id,field,$_FILES['img']
            //判断fields合法性
            $fields = array('kid','biankuan1','biankuan2','biankuan3','biankuan4');
            if(!in_array($post['field'],$fields)){
                $this -> error('参数出错！');
            }
            //先判断是否有文件需要处理
            if(!$file['error']){
                //dump($post['id']);die;
                $data = M('Data') -> field('id,kid,category_id,biankuan1,biankuan2,biankuan3,biankuan4') -> find($post['id']);
                //dump($data);die;
                //取出类别文件夹名
                $folder = $category = M('Category') -> field('folder') -> find($data['category_id']);                
                //dump($folder);die;
                //定义配置
                $cfg = array(
                    //'maxSize' => 3145728,
                    'rootPath' => './Uploads/',
                    //'savePath' => '',
                    //'saveName' => $saveName,
                    'saveName' => array('uniqid',''),
                    'exts' => 'jpg',
                    //'mimes' => 'image/jpeg', //没用
                    'autoSub' => true,
                    'subName' => $folder['folder'],
                    //'replace' => false,//覆盖同名文件
                    //'rootPath'  =>  WORKING_PATH . UPLOAD_ROOT_PATH,
                );
                //dump($cfg);die;
                //实例化上传类
                $upload = new \Think\Upload($cfg);
                //开始上传
                $info = $upload -> uploadOne($_FILES['img']);
                //dump($info);die;
                //判断是否上传成功
                if($info){
                    //删除原有文件
                    if(!is_null($data[$post['field']])){
                        unlink('./Uploads/' . $folder['folder'] . '/' . $data[$post['field']]);
                    }
                    
                    $postData = array();
                    $postData['id'] = $data['id'];
                    $postData[$post['field']] = $info['savename']; //重新保存文件名称
                    $postData['addtime'] = time();//重新保存添加时间
                }
            }
            
            //更新数据
            $result = M('Data') -> save($postData);
            if($result){
                $this -> success('添加成功!',U('Admin/Data/edit/id/'. $post['id']),3);
            }else{
                $this -> error('添加失败!');
            }
        }else{
            $this -> display();
        }
    }
    //删除数据
    public function del(){
        if(IS_POST){
            //post删除
            //接收参数 
            $id = I('post.id');
            //获取数据
            $model = M('Data');
            $data = $model  -> field('t1.*,t2.folder as folder')
                            -> alias('t1')
                            -> join('left join yh_category as t2 on t1.category_id = t2.id')
                            -> where('t1.id = ' . $id)
                            -> find();
            //dump($data);die;
            //删除对应的图片
            if(!is_null($data['kid'])){
                unlink('./Uploads/' . $data['folder'] . '/' . $data['kid']);
            }
            if(!is_null($data['biankuan1'])){
                unlink('./Uploads/' . $data['folder'] . '/' . $data['biankuan1']);
            }
            if(!is_null($data['biankuan2'])){
                unlink('./Uploads/' . $data['folder'] . '/' . $data['biankuan2']);
            }
            if(!is_null($data['biankuan3'])){
                unlink('./Uploads/' . $data['folder'] . '/' . $data['biankuan3']);
            }
            if(!is_null($data['biankuan4'])){
                unlink('./Uploads/' . $data['folder'] . '/' . $data['biankuan4']);
            }

            //删除
            $result = $model -> delete($id);
            if($result){
                //成功
                $this -> success('删除成功！',U('showList'));
            }else{
                $this -> error('删除失败！');
            }
        }else{
            //接收id
            $id = I('get.id');
            //sql=select t1.*,t2.folder as folder from yh_data as t1 left join yh_category as t2 on t1.category_id = t2.id where t1.id = get.id
            //获取数据
            $data = M('Data') -> field('t1.*,t2.folder as folder')
                            -> alias('t1')
                            -> join('left join yh_category as t2 on t1.category_id = t2.id')
                            -> where('t1.id = ' . $id)
                            -> find();
            //dump($data);die;
            //图片路径拼接一下
            $data['kid'] = '/Uploads/' . $data['folder'] . '/' . $data['kid'];
            //dump($data);die;
            $this -> assign('data',$data);
            //展示模板
            $this -> display();
        }
    }

    //excel导入数据库
    public function import(){
        if(IS_POST){
            $post = I('post.');
            if(!$file['error']){
            //定义配置
            $cfg = array(
                //'maxSize' => 3145728,
                'rootPath' => './Uploads/Excel/',
                //'savePath' => '',
                'saveName' => array('uniqid',''),
                'exts' => array('xls','xlsx'),
                //'mimes' => 'image/jpeg', //没用
                'autoSub' => false,
            );
            //dump($cfg);die;
            //实例化上传类
            $upload = new \Think\Upload($cfg);
            //开始上传
            $info = $upload -> uploadOne($_FILES['excelTable']);
            //dump($info);die;
            //判断是否上传成功
            if($info){
                $data = importExcel('./Uploads/Excel/' . $info['savename'],$info['ext']);
                //dump($data);die;
                foreach ($data as $key => $val) {
                    if ($key > 1) {
                        $datas['kid'] = $val['A'];
                        $datas['tuli'] = $val['B'];
                        $datas['yw1'] = $val['C'];
                        $datas['yw2'] = $val['D'];
                        $datas['zhulu'] = $val['E'];
                        $datas['store'] = $val['F'];
                        $datas['beizhu'] = $val['G'];
                        $datas['shidai'] = $val['H'];
                        $datas['xingzhi'] = $val['I'];
                        $datas['zhidi'] = $val['J'];
                        $datas['niushi'] = $val['K'];
                        $datas['guanzhi'] = $val['L'];
                        $datas['diming'] = $val['M'];
                        $datas['xingshi'] = $val['N'];
                        $datas['mingzi'] = $val['O'];
                        $datas['category_id'] = $post['category_id'];
                        $datas['addtime'] = time();
                        
                        $newData[] = $datas;
                    }
                }
                $result = M('Data') -> addAll($newData);
            }
            if($result){
                $this -> success('数据导入成功！',U('showList'));
            }else{
                $this -> error('数据导入失败！');
            }
        }
        }else{
            //展示模板
            $model = M('Category');
            $data = $model -> order('id desc') -> select();
            $this -> assign('data',$data);
            $this -> display();
        }
    }

    //导出数据
    public function export(){
        if(IS_POST){
            $post = I('post.');
            $category = M('Category') -> find($post['category_id']);
            //dump($category);die;
            // excel表头  
            $headArr[] = '文件名';
            $headArr[] = '印文';
            $headArr[] = '著録';
            $headArr[] = '藏所';
            $headArr[] = '备注';
            $headArr[] = '时代';
            $headArr[] = '性质';
            $headArr[] = '质地';
            $headArr[] = '钮式';
            $headArr[] = '边款1';
            $headArr[] = '边款2';
            $headArr[] = '边款3';
            $headArr[] = '边款4';
            // 数据
            $data = M('Data') -> field('kid,yw2,zhulu,store,beizhu,shidai,xingzhi,zhidi,niushi,biankuan1,biankuan2,biankuan3,biankuan4') -> where('category_id = ' . $category['id']) -> select();
            //dump($data);die;
            $filename = $category['name'];
            exportExcel($filename, $headArr, $data); // $filename excel名称 $headArr excel表头
        }else{
            //展示模板
            $model = M('Category');
            $data = $model -> order('id desc') -> select();
            $this -> assign('data',$data);
            $this -> display();
        }
    }
}